package com.boot.config.datasource

import org.apache.ibatis.session.SqlSessionFactory
import org.mybatis.spring.SqlSessionFactoryBean
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
import org.springframework.jdbc.datasource.DataSourceTransactionManager
import tk.mybatis.spring.annotation.MapperScan
import java.util.*
import javax.sql.DataSource

/**
 * @author kawins
 * createTime 2018-12-07 16:07
 */

@Configuration
@MapperScan(basePackages = ["com.boot.mgt.dao"])
class MyBatisConfig {

    @Bean
    @Throws(Exception::class)
    fun sqlSessionFactory(dataSource: DynamicDataSource): SqlSessionFactory? {
        val fb = SqlSessionFactoryBean()
        fb.setDataSource(dataSource)
        val path = PathMatchingResourcePatternResolver()
        fb.setMapperLocations(
                path.getResources("classpath*:/mappers/**/*Mapper.xml"))
        fb.setConfigLocation(path.getResource("classpath:mybatis/mybatis-config.xml"))
        return fb.`object`
    }

    /**
     * 配置事务管理器
     */
    @Bean
    @Throws(Exception::class)
    fun transactionManager(dataSource: DynamicDataSource): DataSourceTransactionManager {
        return DataSourceTransactionManager(dataSource)
    }
}
